package talk.activity;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.gyf.barlibrary.ImmersionBar;

import base.BaseActivity;
import kt.ContentFragment;
import talk.Bean.addFriend;
import talk.Data.Constant;
import talk.Net.HttpRequest;

import com.talk.debby.talk.R;

import talk.View.DrawerViewBuild;
import talk.fragment.FriendListFragment;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.rong.imkit.fragment.ConversationListFragment;
import io.rong.imlib.model.Conversation;

/**
 * Created by debby on 2018/4/12.
 * 描述:聊天主页面
 */

public class HomeActivity extends BaseActivity implements View.OnClickListener {

    private Context context;
    //会话fragment
    private Fragment mConversationFragment = null;
    //列表list
    private List<Fragment> fragments = new ArrayList<>();
    private List<String> items = new ArrayList<>();//tab_home名称
    //标题
    private TextView tv_title;

    private DrawerViewBuild drawerViewBuild;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = this;
        initTitleBar(true);
        setContentView(R.layout.activity_home);
        initData();
        initView();
    }

    private void initView() {
        ViewPager vp_home = findViewById(R.id.vp_home);
        TabLayout tab_home = findViewById(R.id.tab_home);
        tv_title = findViewById(R.id.tv_title);
        //添加好友
        findViewById(R.id.iv_add_friend).setOnClickListener(this);

        //配置ViewPager的适配器
        FragmentPagerAdapter mFragmentPagerAdapter = new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                return fragments.get(position);
            }

            @Override
            public int getCount() {
                return fragments.size();
            }

            @Nullable
            @Override
            public CharSequence getPageTitle(int position) {
                return items.get(position);
            }
        };
        vp_home.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                tv_title.setText(items.get(position));
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        vp_home.setAdapter(mFragmentPagerAdapter);
        tab_home.setupWithViewPager(vp_home);
        SeekBar seekBar = new SeekBar(this);
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
    }

    /**
     * 初始化数据
     */
    private void initData() {
        fragments.add(initConversationList());
        fragments.add(FriendListFragment.getInstance());
        fragments.add(new ContentFragment());
        String[] list = getResources().getStringArray(R.array.tab_name);
        items.addAll(Arrays.asList(list));
        drawerViewBuild = new DrawerViewBuild(this);
        Constant.user = getUser();
    }

    /**
     * 获取会话列表
     *
     * @return 会话列表frament
     */
    private Fragment initConversationList() {
        // appendQueryParameter对具体的会话列表做展示
        if (mConversationFragment == null) {
            ConversationListFragment listFragment = new ConversationListFragment();
            Uri uri = Uri.parse("rong://" + getApplicationInfo().packageName).buildUpon()
                    .appendPath("conversationList")
                    .appendQueryParameter(Conversation.ConversationType.PRIVATE.getName(), "false")//设置私聊会话是否聚合显示
                    .appendQueryParameter(Conversation.ConversationType.GROUP.getName(), "true")
                    .appendQueryParameter(Conversation.ConversationType.DISCUSSION.getName(), "false")//设置私聊会话是否聚合显示
                    .appendQueryParameter(Conversation.ConversationType.SYSTEM.getName(), "false")//设置私聊会是否聚合显示
                    .build();
            listFragment.setUri(uri);
            return listFragment;
        } else {
            return mConversationFragment;
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_add_friend:
                addFriend();
                break;

        }
    }

    private void addFriend() {
        //实例化布局
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_add_friend, null);
        //找到并对自定义布局中的控件进行操作的示例
        final EditText et_add_friend = view.findViewById(R.id.et_add_friend);
        Button bt_add_friend = view.findViewById(R.id.bt_add_friend);

        bt_add_friend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String friendId = et_add_friend.getText().toString().trim();
                HttpRequest.addFriend(Constant.user.getSinfo().getUid(), friendId, new Observer<addFriend>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(addFriend addFriend) {
                        Toast.makeText(context
                                , addFriend.getMsg()
                                , Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
            }
        });

        //创建对话框
        AlertDialog dialog = new AlertDialog.Builder(this).create();
        dialog.setIcon(R.mipmap.chat);//设置图标
        dialog.setTitle("添加好友");//设置标题
        dialog.setView(view);//添加布局
        dialog.show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        initTitleBar(false);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent i = new Intent(Intent.ACTION_MAIN);
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            i.addCategory(Intent.CATEGORY_HOME);
            startActivity(i);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    //沉浸式
    private ImmersionBar mImmersionBar;

    private void initTitleBar(Boolean isInit) {
        if (isInit) {
            mImmersionBar = ImmersionBar.
                    with(this)
                    .statusBarDarkFont(true);
            mImmersionBar.init();   //所有子类都将继承这些相同的属性
        } else {
            if (mImmersionBar != null)
                mImmersionBar.destroy();
        }
    }

}
